package com.example.doctor.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.example.common.entity.Config;
import com.example.common.entity.ConsultationLog;
import com.example.common.entity.DoctorBaseInfo;
import com.example.common.entity.ExInfo;
import com.example.common.entity.Hospital;
import com.example.common.entity.OnlineConsultation;
import com.example.common.entity.OrderMain;
import com.example.common.entity.PatientsInfo;
import com.example.common.entity.Pharmacist;
import com.example.common.entity.RxDrugs;
import com.example.common.entity.RxInfo;
import com.example.common.entity.RxMain;
import com.example.common.support.ApiException;
import com.example.common.utils.CheckUtils;
import com.example.common.utils.IdUtils;
import com.example.common.utils.XmlUtils;
import com.example.common.cqsupervision.dto.ca.Doc.CA;
import com.example.doctor.dto.req.IMSaveReq;
import com.example.doctor.dto.req.SubmitRxOrderRxDrugsReq;
import com.example.doctor.dto.req.SubmitRxReq;
import com.example.doctor.jpa.*;
import com.example.doctor.mapper.IMMapper;
import com.example.doctor.mapper.PatientMapper;
import com.example.doctor.mapper.RxOrderMapper;
import com.example.doctor.service.InquiryService;
import com.example.doctor.utils.UserUtils;
import com.example.common.sendhttp.WxSendMessage;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Value;

@Service
public class InquiryServiceImpl implements InquiryService {
    @Resource
    private UserUtils userUtils;
    @Resource
    IMMapper iMMapper;

    @Resource
    ConfigRepository configRepository;

    @Resource
    OnlineConsultationRepository onlineConsultationRepository;

    @Resource
    OrderMainRepository orderMainRepository;

    @Resource
    ExInfoRepository exInfoRepository;

    @Resource
    PatientsInfoRepository patientsInfoRepository;

    @Resource
    PatientMapper patientMapper;
    @Resource
    private DiseaseInfoRepository diseaseInfoRepository;
    @Resource
    DoctorBaseInfoRepository doctorBaseInfoRepository;

    @Resource
    ConsultationLogRepository consultationLogRepository;

    @Resource
    RxOrderMapper rxOrderMapper;

    @Resource
    HospitalRepository hospitalRepository;

    @Resource
    PharmacistRepository pharmacistRepository;

    @Resource
    RxMainRepository rxMainRepository;

    @Resource
    RxInfoRepository rxInfoRepository;

    @Resource
    RxDrugsRepository rxDrugsRepository;

    @Resource
    WxSendMessage wxSendMessage;

    
    @Value("${drugmappID}")
    private String drugmappID;

    @Value("${drugmappsecret}")
    private String drugmappsecret;


    @Transactional(rollbackFor = Exception.class, transactionManager = "jpaTransactionManager")
    private void FinInquiry(long UID) {
        List<OnlineConsultation> list = onlineConsultationRepository.timeOutOrder(UID);
        if (list == null || list.size() == 0)
            return;

        List<OrderMain> olist = orderMainRepository.queryOrderByIds(list.stream().map(m -> m.getOrderNo()).collect(Collectors.toList()));

        list.forEach(m -> {
            m.setOcStatus(2);
            m.setFactFinishTime(m.getEndTime());
            olist.stream().filter(n -> n.getOrderNo().equals(m.getOrderNo())).findFirst().get().setOcStatus(2);
        });

        try {
            onlineConsultationRepository.saveAll(list);
            orderMainRepository.saveAll(olist);
        } catch (Exception e) {
            //TODO: handle exception
        }
    }

    @Override
    public List<Map<String, Object>> IMList(long UID) {
        FinInquiry(UID);
        List<Map<String, Object>> list = iMMapper.IMList(UID);
        if (list == null || list.size() == 0)
            return list;

        String OCIDs = String.join(",", list.stream().map(e -> e.get("OCID").toString()).collect(Collectors.toList()));
        List<Map<String, Object>> IMLog = iMMapper.LastIM(OCIDs);

        list.forEach(m -> {
            List<Map<String, Object>> imlist = IMLog.stream().filter(n -> (long) m.get("OCID") == (long) n.get("OCID")).collect(Collectors.toList());
            Map<String, Object> im = null;
            if (imlist != null && imlist.size() > 0)
                im = imlist.get(0);
            m.put("CType", im != null ? im.get("CType") : 0);
            m.put("IMContent", im != null ? im.get("IMContent") : "");
            m.put("LastTime", im != null ? ((Date) im.get("CreateTime")).getTime() : -1);
        });
        list.sort((m1, m2) -> ((Long) m1.get("LastTime")).compareTo(((long) m2.get("LastTime"))));
        // Collections.sort(list, Collections.reverseOrder());
        return list;
    }

    @Override
    public List<Map<String, Object>> NoReceiveList(long UID) {
        List<Map<String, Object>> IMLog = iMMapper.NoReceiveList(UID);
        return IMLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "jpaTransactionManager")
    public Map<String, Object> Receive(long UID, String OrderNO) {
        Config dconfig = configRepository.findById(UID).orElseThrow(() -> new ApiException(10000, "医生信息不完整"));
        int Minute = 0;
        OnlineConsultation im = onlineConsultationRepository.findByOrderNo(OrderNO);
        if (im.getOcStatus() != 0)
            throw new ApiException(10000, "问诊已不能接诊");
        if (onlineConsultationRepository.HaveInquiry(im.getDcId(), im.getPid()) > 0)
            throw new ApiException(10000, "相同患者已存在有效问诊，不能接诊");

        OrderMain order = orderMainRepository.findById(OrderNO).orElseThrow(() -> new ApiException(10000, "订单不存在"));
        ExInfo dexInfo = exInfoRepository.findById(UID).orElseThrow(() -> new ApiException(10000, "医生信息不完整"));

        switch (im.getAType()) {
            case 10:
                Minute = dconfig.getReferralValid();
                break;
            case 11:
                Minute = dconfig.getImgTextValid();
                break;
            case 12:
                Minute = dconfig.getPhoneValid();
                break;
            case 13:
                Minute = dconfig.getVideoValid();
                break;
        }

        Date now = new Date();
        im.setStartTime(now);
        Calendar time = Calendar.getInstance();
        time.setTime(im.getStartTime());
        time.add(Calendar.MINUTE, Minute);

        im.setOcStatus(1);
        im.setEndTime(time.getTime());
        im.setLastTime(Minute * 60);

        order.setReceiveTime(now);
        order.setReceive(Minute);
        order.setOcStatus(1);

        dexInfo.setService(dexInfo.getService() + 1);

        dexInfo.setReceive(new BigDecimal((double) dexInfo.getService() * 100.00 / (double) dexInfo.getInquiry()));

        try {
            onlineConsultationRepository.save(im);
            orderMainRepository.save(order);
            exInfoRepository.save(dexInfo);
        } catch (Exception e) {
            throw new ApiException(10000, "接诊异常，请稍后再试");
        }
        // 给患者发 医生接诊提醒


        Map<String, Object> re = new HashMap<>();
        re.put("Re", true);
        return re;
    }

    @Override
    public Map<String, Object> Patients(long UID, String OrderNO) {
        PatientsInfo info = patientsInfoRepository.findByOrderNo(OrderNO);
        OnlineConsultation im = onlineConsultationRepository.findByOrderNo(OrderNO);
        OrderMain orderobj = orderMainRepository.findById(OrderNO).orElseThrow(() -> new ApiException(10000, "订单不存在"));
        Map<String, Object> Client = patientMapper.ClientInfo(info.getPid());

        Map<String, Object> Patient = new HashMap<>();
        Patient.put("HXID", Client.get("HXID"));
        Patient.put("Header", Client.get("Header"));
        Patient.put("PID", info.getPid());
        Patient.put("Name", info.getName());
        Patient.put("Sex", info.getSex());
        Patient.put("Age", info.getAge());
        Patient.put("First", info.getFirst());
        Patient.put("Chiefcomplaint", info.getChiefComplaint());
        Patient.put("AType", orderobj.getAType());
        Patient.put("OCID", orderobj.getOcId());
        Patient.put("imStartTime", im.getOcStatus() != 0 ? im.getStartTime().getTime() : 0);
        Patient.put("imEndTime", im.getOcStatus() == 1 ? im.getEndTime().getTime() : im.getFactFinishTime().getTime());
        Patient.put("imLave", im.getOcStatus() != 0 ? (im.getEndTime().getTime() - im.getStartTime().getTime()) % (1000 * 60 * 60) : 0);

        DoctorBaseInfo d = doctorBaseInfoRepository.findById(UID).orElseThrow(() -> new ApiException(10000, "医生信息不完整"));

        Map<String, Object> res = new HashMap<>();
        res.put("Patient", Patient);
        res.put("ZPrescription", d.getZprescription());
        res.put("XPrescription", d.getXprescription());

        return res;
    }

    @Override
    public List<Map<String, Object>> IMLogList(long OCID, int page, int limit) {
        int skip = (page - 1) * limit;
        if (skip < 0) skip = 0;

        List<Map<String, Object>> list = iMMapper.IMLogList(OCID, skip, limit);
        if (list == null || list.size() == 0)
            return list;

        list.forEach(m -> m.put("CreateTime", ((Date) m.get("CreateTime")).getTime()));
        return list;
    }

    @Override
    public Map<String, Object> IMSave(IMSaveReq req) {
        ConsultationLog obj = new ConsultationLog();
        obj.setId(IdUtils.generateId());
        obj.setOcId(req.getOCID());
        obj.setImType(2);
        obj.setFromHx(req.getFromHX());
        obj.setToHx(req.getToHX());
        obj.setCreateTime(new Date());
        obj.setImContent(req.getIMContent());
        obj.setHaveRead(false);
        obj.setCType(req.getCType());
        obj.setDType(req.getDType());
        obj.setRxOrderNo(req.getRxOrderNO());

        try {
            consultationLogRepository.save(obj);
        } catch (Exception e) {
            return null;
        }

        Map<String, Object> res = new HashMap<>();
        res.put("Save", true);
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "jpaTransactionManager")
    public Map<String, Object> IMFinish(String OrderNO) {
        OnlineConsultation im = onlineConsultationRepository.findByOrderNo(OrderNO);
        im.setOcStatus(2);
        im.setFactFinishTime(new Date());

        OrderMain order = orderMainRepository.findById(OrderNO).orElseThrow(() -> new ApiException(10000, "订单不存在"));
        order.setOcStatus(2);

        try {
            onlineConsultationRepository.save(im);
            orderMainRepository.save(order);
        } catch (Exception e) {
            throw new ApiException(10000, "结束问诊异常，请稍后再试");
        }

        Map<String, Object> res = new HashMap<>();
        res.put("Save", true);
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "jpaTransactionManager")
    public Map<String, Object> SubmitRx(long UID, SubmitRxReq req) {
        Map<String, Object> obj = rxOrderMapper.OrderClientInfo(req.getRxmain().getOrderNO());
        Hospital hospital = hospitalRepository.findByLast();
        List<Pharmacist> pharmacist = pharmacistRepository.findByAllNoDisable();
        if (pharmacist.size() == 0)
            throw new ApiException(10000, "用药建议提交失败，没有可用的药剂师");

        Pharmacist chkd;
        int idx = 0;
        Random rd = new Random();
        int OnlineCount = pharmacist.stream().filter(m -> m.getIsOnline()).collect(Collectors.toList()).size();
        if (OnlineCount > 0) {
            idx = rd.nextInt(OnlineCount);
            chkd = pharmacist.stream().filter(m -> m.getIsOnline()).collect(Collectors.toList()).get(idx);
        } else {
            idx = rd.nextInt(pharmacist.size() - 1);
            chkd = pharmacist.get(idx);
        }

        Date now = new Date();
        RxMain rxmain = new RxMain();
        rxmain.setRxOrderNO("R" + ((req.getRxmain().getDType() == 1 || req.getRxmain().getDType() == 3) ? "Z" : req.getRxmain().getDType() == 2 ? "X" : "") + IdUtils.generateId());
        rxmain.setOrderNO(req.getRxmain().getOrderNO());
        rxmain.setDialectical(req.getRxmain().getDialectical());
        rxmain.setDisCode(req.getRxmain().getDisCode());
        rxmain.setZDialectical(req.getRxmain().getZDialectical());
        rxmain.setZDisCode(req.getRxmain().getZDisCode());
        rxmain.setZDialectics(req.getRxmain().getZDialectics());
        rxmain.setZDialecticsCode(req.getRxmain().getZDialecticsCode());
        rxmain.setDisIds(req.getRxmain().getDisIDS());
        rxmain.setSuggest(req.getRxmain().getSuggest());
        rxmain.setMedWay(req.getRxmain().getMedWay());
        rxmain.setDType(req.getRxmain().getDType());
        rxmain.setSystemStatus(1);
        rxmain.setOrderPayTime(null);
        rxmain.setFreight(new BigDecimal(0));
        rxmain.setSalePrice(new BigDecimal(0));
        rxmain.setCreateTime(now);
        rxmain.setOrderBack(0);
        rxmain.setUOpenTid(obj.get("OpenID").toString());
        rxmain.setBadge(hospital.getBadge());
        rxmain.setOcId((Long) obj.get("OCID"));
        rxmain.setOpenDoctor(obj.get("Name").toString());
        rxmain.setAskDoctor(obj.get("Name").toString());
        rxmain.setZyszms(req.getRxmain().getZyszms());
        rxmain.setBzfx(req.getRxmain().getBzfx());
        rxmain.setJzzdsm(req.getRxmain().getJzzdsm());
        rxmain.setClcs(req.getRxmain().getClcs());
        rxmain.setSfxylygc(req.getRxmain().getSfxylygc());

        DoctorBaseInfo doctor = doctorBaseInfoRepository.findByDcId(UID);
        CA ca = new CA();
        ca.setMedicalRecordNo(rxmain.getRxOrderNO());
        ca.setDoctorCode(doctor.getDcId().toString());
        ca.setDoctorName(doctor.getName());
        ca.setPatientName(obj.get("pName").toString());
        ca.setPatientSFZH(obj.get("idNo").toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ca.setRecipeDate(sdf.format(rxmain.getCreateTime()));

        List<CA.Diagnosis> diagnosisList = new ArrayList<>();
        CA.Diagnosis diagnosis = new CA.Diagnosis();
        diagnosis.setDiagnosisCode(rxmain.getDisCode());
        diagnosis.setDiagnosisName(rxmain.getDialectical());
        diagnosisList.add(diagnosis);
        if (rxmain.getDType() == 1 || rxmain.getDType() == 3) {
            diagnosis = new CA.Diagnosis();
            diagnosis.setDiagnosisCode(rxmain.getZDisCode());
            diagnosis.setDiagnosisName(rxmain.getZDialectical());
            diagnosisList.add(diagnosis);
        }
        ca.setDiagnosisList(diagnosisList);


        rxmain.setChkDcId(chkd.getDcId());
        rxmain.setChkDoctor(chkd.getName());
        rxmain.setChkStatus(0);
        /// 不能自动审方
        // if (chkd.getIsExamine()) {
        //     rxmain.setChkTime(now);
        //     rxmain.setChkStatus(1);
        // }


        RxInfo rxinfo = new RxInfo();
        rxinfo.setRxOrderNo(rxmain.getRxOrderNO());
        rxinfo.setCreateTime(now);
        rxinfo.setDrugType(req.getRxmain().getDType().toString());
        rxinfo.setDoes(req.getRxinfo().getDoes());
        rxinfo.setDayCount(req.getRxinfo().getDayCount());
        rxinfo.setAvoid(req.getRxinfo().getAvoid());
        rxinfo.setUseTime(req.getRxinfo().getUseTime());
        rxinfo.setCook(req.getRxinfo().getCook());
        rxinfo.setDrugInfo(req.getRxinfo().getDrugInfo());
        rxinfo.setTotalDoes(req.getRxinfo().getTotalDoes());
        rxinfo.setMedWay(req.getRxinfo().getMedWay());

        String DrugIDs = String.join(",", req.getRxdrugs().stream().map(m -> m.getDrugID() + "").collect(Collectors.toList()));
        List<Map<String, Object>> sysDrug = new ArrayList<>();
        if (rxmain.getDType() == 1)
            sysDrug = rxOrderMapper.zBaseInfo(DrugIDs);
        if (rxmain.getDType() == 2 || rxmain.getDType() == 3)
            sysDrug = rxOrderMapper.xBaseInfo(DrugIDs);

        List<CA.Drug> drugs = new ArrayList<>();
        List<RxDrugs> rxdrugs = new ArrayList<>();
        sysDrug.forEach(m -> {
            long DrugID = (long) m.get("DrugID");
            BigDecimal Price = new BigDecimal(m.get("Price").toString());
            RxDrugs d = new RxDrugs();
            d.setId(IdUtils.generateId());
            d.setRxOrderNo(rxmain.getRxOrderNO());
            d.setPrice(Price);
            SubmitRxOrderRxDrugsReq rxdrugreq = req.getRxdrugs().stream().filter(n -> n.getDrugID() == DrugID).collect(Collectors.toList()).get(0);
            d.setType(req.getRxmain().getDType());
            d.setDrugId(DrugID);
            d.setDrugName(rxdrugreq.getDrugName());
            d.setSpec(rxdrugreq.getSpec());
            d.setNum(rxdrugreq.getNum());
            d.setGuild(null == rxdrugreq.getGuild() ? 0 : rxdrugreq.getGuild() ? 1 : 0);
            d.setMedWay(rxdrugreq.getMedWay());
            d.setFreq(rxdrugreq.getFreq());
            d.setDoes(rxdrugreq.getDoes());
            d.setDoesUnit(rxdrugreq.getDoesUnit());
            d.setDay(rxdrugreq.getDay());
            d.setRemark(rxdrugreq.getRemark());
            rxdrugs.add(d);
            rxmain.setSalePrice(rxmain.getSalePrice().add(d.getPrice().multiply(new BigDecimal(d.getNum()))));

            CA.Drug drug = new CA.Drug();
            drug.setHospitalDrugCode(d.getDrugId().toString());
            drug.setDrugCommonName(d.getDrugName());
            drug.setPrice(d.getPrice().toString());
            drug.setDeliverNumUnit(d.getNum().toString());
            drug.setMoney(d.getPrice().multiply(new BigDecimal(d.getNum())).toString());
            drugs.add(drug);
        });

        ExInfo dexInfo = exInfoRepository.findById(UID).orElseThrow(() -> new ApiException(10000, "医生信息不完整"));
        dexInfo.setPrescription(dexInfo.getPrescription() + 1);

        ca.setDrugList(drugs);

        rxmain.setRecipeDocSignatureXml(XmlUtils.convertToXml(ca));
        rxmain.setIsRecipeDocCa(false);
        rxmain.setIsTrialPharmCa(false);

        try {
            rxMainRepository.save(rxmain);
            rxInfoRepository.save(rxinfo);
            rxDrugsRepository.saveAll(rxdrugs);
            exInfoRepository.save(dexInfo);
        } catch (Exception e) {
            throw new ApiException(10000, "用药建议提交失败");
        }

        Map<String, Object> res = new HashMap<>();
        res.put("Save", true);
        res.put("RxOrderNO", rxmain.getRxOrderNO());
        if(req.getIsPc()){
            res.put("wxCode", createWxUnlimited(rxmain.getRxOrderNO(), doctor));
        }
        return res;
    }

    @Value("${mappID}")
    private String mappID;

    @Value("${mappsecret}")
    private String mappsecret;
    
    private String createWxUnlimited(String rxOrderNo, DoctorBaseInfo doctor) {
        String token = wxSendMessage.getAccessToken(mappID, mappsecret);
        Map<String, String> req = new HashMap<>();
        req.put("scene", rxOrderNo); 
        req.put("page", "subpages/main/prescribe/sign/handSign");
        return wxSendMessage.createWxaCode(token, req);
    }
  
    @Override
    public Map<String, Object> ZRxDetail(String RxOrderNO) {
        Map<String, Object> PatientsInfo = rxOrderMapper.PatientsInfo(RxOrderNO);
        RxMain info = rxMainRepository.findById(RxOrderNO).orElseThrow(() -> new ApiException(10000, "订单不存在"));
        RxInfo rxinfo = rxInfoRepository.findById(RxOrderNO).orElseThrow(() -> new ApiException(10000, "订单不存在"));
        StringBuilder sb = new StringBuilder();
        List<Long> disIds = Arrays.stream(info.getDisIds().split(",")).map(Long::parseLong)
                .collect(Collectors.toList());
        diseaseInfoRepository.findByIdIn(disIds).stream()
                .map(m -> m.getCode() + " " + m.getDiseaseName()).forEach(m -> {
            sb.append(m);
        });
        Map<String, Object> detail = new HashMap<>();
        detail.put("RxOrderNO", PatientsInfo.get("RxOrderNO"));
        detail.put("Name", PatientsInfo.get("Name"));
        detail.put("Sex", PatientsInfo.get("Sex"));
        detail.put("Age", PatientsInfo.get("Age"));
        detail.put("depName", PatientsInfo.get("depName"));
        detail.put("CreateTime", PatientsInfo.get("CreateTime"));
        detail.put("Dialectical", sb.toString());
        detail.put("zDialectical", info.getZDialectical());
        detail.put("zDialectics", info.getZDialectics());
        detail.put("SalePrice", info.getSalePrice());
        detail.put("Badge", info.getBadge());
        detail.put("OpenDoctor", info.getOpenDoctor());
        detail.put("ChkStatus", info.getChkStatus());
        detail.put("ChkDoctor", info.getChkDoctor());
        detail.put("FailureReason", info.getFailureReason());
        detail.put("FailureRemark", info.getFailureRemark());
        detail.put("DialecticalRemark", info.getDialecticalRemark());
        detail.put("Avoid", rxinfo.getAvoid());
        detail.put("MedTime", rxinfo.getUseTime());
        detail.put("DrugInfo", rxinfo.getDrugInfo());
        detail.put("TotalDoes", rxinfo.getTotalDoes());
        detail.put("DayCount", rxinfo.getDayCount());
        detail.put("Does", rxinfo.getDoes());
        detail.put("MedWay", rxinfo.getMedWay());

        return detail;
    }

    @Override
    public Map<String, Object> XRxDetail(String RxOrderNO) {
        Map<String, Object> PatientsInfo = rxOrderMapper.PatientsInfo(RxOrderNO);
        CheckUtils.checkNullReturn(RxOrderNO, new ApiException(10000, "订单号不能为空"));
        RxMain info = rxMainRepository.findById(RxOrderNO).orElseThrow(() -> new ApiException(10000, "订单不存在"));
        List<Long> disIds = Arrays.stream(info.getDisIds().split(",")).map(Long::parseLong)
                .collect(Collectors.toList());
        StringBuilder sb = new StringBuilder();
        diseaseInfoRepository.findByIdIn(disIds).stream()
                .map(m -> m.getCode() + " " + m.getDiseaseName()).forEach(m -> {
            sb.append(m);
        });
        List<RxDrugs> rxdrugs = rxDrugsRepository.findByRxOrderNo(RxOrderNO);
        List<Map<String, Object>> RxDrugs = new ArrayList<>();
        rxdrugs.forEach(m -> {
            Map<String, Object> rx = new HashMap<>();
            rx.put("DrugName", m.getDrugName());
            rx.put("Spec", m.getSpec());
            rx.put("Num", m.getNum());
            rx.put("Suggest", m.getMedWay() + "；每日" + m.getFreq() + "；" + m.getDoes() + m.getDoesUnit() + "/次；" + m.getDay() + "天");
            rx.put("Remark", m.getRemark());
            RxDrugs.add(rx);
        });

        Map<String, Object> detail = new HashMap<>();
        detail.put("RxOrderNO", PatientsInfo.get("RxOrderNO"));
        detail.put("Name", PatientsInfo.get("Name"));
        detail.put("Sex", PatientsInfo.get("Sex"));
        detail.put("Age", PatientsInfo.get("Age"));
        detail.put("depName", PatientsInfo.get("depName"));
        detail.put("CreateTime", PatientsInfo.get("CreateTime"));
        detail.put("Dialectical", sb.toString());
        detail.put("zDialectical", info.getZDialectical());
        detail.put("zDialectics", info.getZDialectics());
        detail.put("RxDrugs", RxDrugs);
        detail.put("SalePrice", info.getSalePrice());
        detail.put("Badge", info.getBadge());
        detail.put("OpenDoctor", info.getOpenDoctor());
        detail.put("ChkStatus", info.getChkStatus());
        detail.put("ChkDoctor", info.getChkDoctor());
        detail.put("FailureReason", info.getFailureReason());
        detail.put("FailureRemark", info.getFailureRemark());

        return detail;
    }

    @Override
    public List<Map<String, Object>> IMOrderList(long UID, int page, int limit) {
        int haveEnd = onlineConsultationRepository.haveInquiryEnd(UID);
        if (haveEnd > 0)
            onlineConsultationRepository.EndInquiry(UID);

        int skip = (page - 1) * limit;
        if (skip < 0) skip = 0;
        List<Map<String, Object>> list = rxOrderMapper.IMOrderList(UID, skip, limit);

        Date now = new Date();
        List<Map<String, Object>> res = new ArrayList<>();
        list.forEach(m -> {
            Map<String, Object> map = new HashMap<>();
            map.put("OrderNO", m.get("OrderNO"));
            map.put("OCID", m.get("OCID"));
            map.put("CreateTime", m.get("CreateTime"));
            map.put("AskMoney", m.get("AskMoney"));
            map.put("Name", m.get("Name"));
            map.put("Sex", m.get("Sex"));
            map.put("Age", m.get("Age"));
            map.put("Status", (int) m.get("OCStatus") == 1 && ((Date) m.get("imbeg")).getTime() > now.getTime() ? "预约中" : (int) m.get("OCStatus") == 1 && ((Date) m.get("imbeg")).getTime() < now.getTime() && ((Date) m.get("imend")).getTime() > now.getTime() ? "接诊中" : (int) m.get("OCStatus") == 2 && (int) m.get("IsComment") == 0 ? "待评价" : "已评价");

            res.add(map);
        });
        return res;
    }

    @Override
    public Map<String, Object> IMOrderDetail(String OrderNO) {
        OrderMain order = orderMainRepository.findById(OrderNO).orElseThrow(() -> new ApiException(10000, "订单不存在"));
        PatientsInfo patient = patientsInfoRepository.findByOrderNo(OrderNO);
        OnlineConsultation im = onlineConsultationRepository.findByOrderNo(OrderNO);

        Map<String, Object> res = new HashMap<>();
        res.put("OCStatus", im.getOcStatus());
        res.put("Name", patient.getName());
        res.put("Chiefcomplaint", patient.getChiefComplaint());
        res.put("CreateTime", order.getCreateTime());
        res.put("ImCreateTime", im.getCreateTime());
        res.put("AskMoney", order.getAskMoney());

        return res;
    }

    @Override
    public Boolean haveTongueImg(String OrderNO) {
        PatientsInfo info = patientsInfoRepository.findByOrderNo(OrderNO);
        return info.getTongueImg() != null && !info.getTongueImg().isEmpty();
    }

    @Override
    public List<Map<String, Object>> allIMList(Date beg, Date end, String name, int ocStatus, int aType) {
        long UID = userUtils.getUser().getDcId();
        FinInquiry(UID);

        if (beg != null && end != null) {
            Calendar ca = Calendar.getInstance();
            ca.setTime(end);
            ca.add(Calendar.DAY_OF_MONTH, 1);
            end = ca.getTime();
        }
        List<Map<String, Object>> list = iMMapper.allIMList(beg, end, name, ocStatus, UID, aType);
        if (list == null || list.size() == 0)
            return list;

        String OCIDs = String.join(",", list.stream().map(e -> e.get("OCID").toString()).collect(Collectors.toList()));
        List<Map<String, Object>> IMLog = iMMapper.LastIM(OCIDs);

        list.forEach(m -> {
            List<Map<String, Object>> imlist = IMLog.stream().filter(n -> (long) m.get("OCID") == (long) n.get("OCID")).collect(Collectors.toList());
            Map<String, Object> im = null;
            if (imlist != null && imlist.size() > 0)
                im = imlist.get(0);
            m.put("CType", im != null ? im.get("CType") : 0);
            m.put("IMContent", im != null ? im.get("IMContent") : "");
            m.put("LastTime", im != null ? ((Date) im.get("CreateTime")).getTime() : -1);
        });
        list.sort((m1, m2) -> ((Long) m2.get("LastTime")).compareTo(((long) m1.get("LastTime"))));
        // Collections.sort(list, Collections.reverseOrder());
        list.sort((m1, m2) -> ((Integer) m1.get("ocStatus")).compareTo((Integer) (m2.get("ocStatus"))));
        return list;
    }

    @Override
    public Boolean isCaSess(String rxOrderNo){
        RxMain rx = rxMainRepository.findById(rxOrderNo).orElseThrow(() -> new ApiException(10000, "订单不存在"));
        return rx.getIsRecipeDocCa();
    }

    @Override
    public Map<String,Object> getCaOrder(String rxorderno){
        RxMain rx = rxMainRepository.findById(rxorderno).orElseThrow(() -> new ApiException(10000, "订单不存在"));
        OrderMain order = orderMainRepository.findById(rx.getOrderNO()).orElseThrow(() -> new ApiException(10000, "订单不存在"));
        DoctorBaseInfo doc = doctorBaseInfoRepository.findById(order.getDcId()).orElseThrow(() -> new ApiException(10000, "订单不存在"));

        Map<String, Object> res = new HashMap<>();
        res.put("RxOrderNO", rx.getRxOrderNO());
        res.put("OpenId", doc.getOpenId());
        res.put("Phone", doc.getPhone());

        return res;
    }
}
